package cn.yza.设计模式.单例模式;

import java.util.concurrent.atomic.AtomicLong;

/** 懒汉式
 * @author Honglixi
 * @create 2021-10-25 13:07
 */
public class SingletonTest01 {

    private AtomicLong id = new AtomicLong(0);
    private static SingletonTest01 instance;
    private SingletonTest01() {}
    //同步方法
    public static synchronized SingletonTest01 getInstance() {
        if (instance == null) {
            instance = new SingletonTest01();
        }
        return instance;
    }

    public long getId() {
        return id.incrementAndGet();
    }
}


// 懒汉式(线程安全，同步代码块)
class LazySingleton {
    private static LazySingleton instance;

    private LazySingleton() {}

    public static LazySingleton getInstance() {
        if (instance == null) {
            synchronized (LazySingleton.class) {
                instance = new LazySingleton();
            }
        }
        return instance;
    }
}

//最基本的一种懒汉式，线程不安全
class Singleton01 {
    private static Singleton01 instance;

    private Singleton01() {
    }

    // 提供一个静态的公有方法，当使用到该方法时，才去创建 instance
    // 即懒汉式
    public static Singleton01 getInstance() {
        if (instance == null) {
            instance = new Singleton01();
        }
        return instance;
    }
}